<template>
  <div class="search-suggestion">
    <van-cell-group
      class="cell-list"
    >
      <van-cell
      v-for="(item, index) in suggestionList"
      :key="index"
      icon="search"
      @click="$emit('search', item)"
      >
        <div slot="title" v-html="highLight(item)"></div>
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { getSearchSuggestion } from '@/api/search'
import { debounce } from 'lodash'
export default {
  name: 'SearchSuggestion',
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      suggestionList: []
    }
  },
  watch: {
    searchText: {
      // 固定函数，当searchText改变时会触发
      handler: debounce(function (value) {
        this.loadSearchSuggestions(value)
      }, 500),
      immediate: true // 第一次监听就触发
    }
  },
  methods: {
    async loadSearchSuggestions (q) {
      try {
        const { data } = await getSearchSuggestion(q)
        this.suggestionList = data.data.options
      } catch (err) {
        this.$toast('获取建议失败')
      }
    },
    highLight (text) {
      const highLightStr = `<span style='color: #3296fa'>${this.searchText}</span>`
      const reg = new RegExp(this.searchText, 'gi')
      return text.replace(reg, highLightStr)
    }
  }
}
</script>

<style scoped lang="less">
 .search-suggestion {
  margin-top: 10px;
  /deep/ .van-cell {
   height: 85px;
   .van-icon-search {
     margin-right: 15px;
     color: #c9c9c9;
     font-size: 30px;
   }
   .van-cell__title {
     font-size: 25px;
     color: #333;
   }
  }
}
</style>
